package com.demo.tests.base;

import com.demo.config.ApiEndpoints;
import com.demo.config.ApiHeaders;
import com.demo.utils.LogUtils;
import io.qameta.allure.Allure;
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import org.apache.logging.log4j.Logger;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
import com.demo.config.ApiConfig;

public class BaseLogin {

    private static final Logger log = LogUtils.getLogger();

    @Test(groups = "Login")
    public void testLogin() {
        SoftAssert softAssert = new SoftAssert();

        // 1. 构造请求参数
        String username = "admin";
        String password = "8i4De25KlVQVwqTDgTNGqw==";
        String requestBody = String.format("{\"username\":\"%s\",\"password\":\"%s\"}", username, password);

        // 2. 发送请求（添加必要的请求头）
        Response response = RestAssured.given()
                .header("Accept", "application/json")
                .header("Content-Type", "application/json")
                .header("Origin", "http://10.59.9.21")  // 匹配跨域配置的origin
                .header("Referer", "http://10.59.9.21/dist")  // 前端页面来源
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0")
                .header("Cache-Control", "no-cache")
                .header("Pragma", "no-cache")
                .body(requestBody)
                .post(ApiEndpoints.getFullUrl(ApiEndpoints.Login_POST));

        // 3. 验证响应
        softAssert.assertEquals(response.statusCode(),
                200,
                String.format("HTTP状态码不匹配，实际: %d", response.statusCode())
        );

        // 打印并记录响应信息
        String responseBody = response.asPrettyString();
        Allure.addAttachment("响应体", responseBody);
        log.info("API响应:\n{}", responseBody);
        // 4. 提取token并存储到ApiConfig
        JsonPath jsonPath = response.jsonPath();
        String token = jsonPath.getString("token");
        log.info(token);
        if (token != null && !token.isEmpty()) {
//            ApiConfig.TOKEN = token; // 存储到ApiConfig
            log.info("成功提取token并存储到ApiConfig");
        } else {
            log.error("响应中未找到token字段");
            softAssert.fail("登录成功但未返回token");
        }

        // 可添加对响应体中"用户名不存在"的断言判断
        softAssert.assertFalse(!responseBody.contains("登录成功"), "登录成功");

        softAssert.assertAll();
    }   
}